package aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 1.implements lock
 * 2.写一个静态内部类，继承AbstractQueuedSynchronizer
 */
public class CreateLock  implements Lock {

    private class Sync extends AbstractQueuedSynchronizer{
        @Override
        protected boolean tryAcquire(int arg) {//加锁
            if (!Thread.currentThread().getName().startsWith("like-lisensen-your-head")){
                //log：请以like-lisensen-your-head开头
                return false;
            }
            if (compareAndSetState(0,arg)){
                setExclusiveOwnerThread(Thread.currentThread());//领结婚证，设置当前线程为执行线程
                return true;//加锁成功
            }
            return false;//加锁失败
        }


        @Override
        protected boolean tryRelease(int arg) {//解锁
            if (getState()==0){//压根没锁
                throw new IllegalStateException();
            }
            //此处的set为什么不用cas？
            //因为既然能够解锁，说明你本身就持有锁，既然你持有锁，就说明你有一个单独的私人的单线程
            //的执行空间，那你想干啥就干啥呗。
            setState(0);
            //setExclusiveOwnerThread(null);//伏笔，源码时候说
            return true;
        }


        protected Condition getConditon(){
            return new ConditionObject();
        }

    }

    private Sync sync = new Sync();//创建我们的内部类
    @Override
    public void lock() {
        sync.acquire(1);//模板方法
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);//模板方法
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));//模板方法
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);//模板方法
    }

    @Override
    public void unlock() {
        sync.release(1);//模板方法
    }

    @Override
    public Condition newCondition() {
        return  sync.getConditon();
    }
}
